<?php
/**
 * Created by PhpStorm.
 * User: Keter
 * Date: 2016/9/8
 * Time: 21:42
 */
class PaijuLog extends DatabaseBase
{
    /**
     * 牌组表名
     */
    const TALBE_NAME_ZU = 'log_user_paiju';

    /**
     * 牌局表名
     */
     const TALBE_NAME_JU = 'log_paiju';

    /**
     * 牌组分表名
     * @var
     */
    public $zuTable;

    /**
     * 牌局分表名
     * @var
     */
    public $juTable;

    public function __construct()
    {
        parent::__construct();
        $this->initMysql();
    }

    /**
     * 重写isRedisLog()
     * @param bool $enabled
     */
    public function isRedisLog($enabled = true)
    {
        parent::isRedisLog($enabled);
        $this->mysql('logs')->isRedisLog($enabled);
    }

    /**
     * 设置表名
     * @param $time
     */
    public function setTableName($time='')
    {
        if ($time) {
            $this->zuTable = self::TALBE_NAME_ZU . '_' . date('Ym', $time);
            $this->juTable = self::TALBE_NAME_JU . '_' . date('Ymd', $time);
        } else {
            //$this->zuTable = self::TALBE_NAME_ZU;
            //修改为按月分表存储 
            $this->zuTable = self::TALBE_NAME_ZU . '_' . date('Ym');
            $this->juTable = self::TALBE_NAME_JU;
        }
    }

    /**
     * 保存牌局
     * @param $data
     * @return bool
     */
    public function savePaijuLog($data)
    {
        $where = array(
            'paiZuID' => $data['paiZuID'],
            'seq' => $data['seq']
        );

        /**
         * 保存数据
         */
        $data['uids'] = json_encode($data['uids'], JSON_UNESCAPED_UNICODE);
        $data['detail'] = json_encode($data['detail'], JSON_UNESCAPED_UNICODE);
        $len = strpos($data['paiZuID'], '_');
        $len = $len > 10 ? 0 : $len;
        $timestamp = $len > 0 ? substr($data['paiZuID'], 0, $len) : 0; //add by tmac
        $juData = [
            'paizu_id' => $data['paiZuID'],
            'seq' => $data['seq'],
            'creator' => (integer)$data['creator'],
            'room_id' => $data['roomID'],
            'server_id' => $data['serverID'],
            'uids' => $data['uids'],
            'time' => date("Y-m-d H:i:s", $data['time']),
            'detail' => base64_encode( $data['detail']),
            'juShu' => (integer)$data['juShu'],
            'paizu_time' => (integer)$timestamp, //新增牌组创建，time
            'isMatch' => $data['isMatch'], //新增切磋场、约战对局记录类型区分
            'reward' => $data['reward'], //新增钻石奖励数
            'clubID' => $data['clubID'], //新增俱乐部Id clubID
            'clubName' => $data['clubName'], //新增俱乐部名称 clubName
            'clubConfigID' => $data['clubConfigID'], //新增俱乐部Id clubID
            'hexWanFa' => $data['hexWanFa'], //新增俱乐部名称 clubName
            //clubID,clubName
        ];
        
        $exists = false;
        if ($exists) {
            unset($juData['paiZuID'], $juData['seq']);
            $result = $this->mysql('logs')->update($this->juTable, $juData, $where);
        } else {

            $result = $this->mysql('logs')->insert($this->juTable, $juData);
        }

        if (!$result) {
            $this->e('save_error', $this->mysql('logs')->error());
            $this->e('牌局日志保存失败', $juData);
            return [];
        }

        $pay_type = isset($data['payType']) ? (integer)$data['payType'] : 0;
        // 保存支付类型日志
        $payData = [
            'paizu_id' => $data['paiZuID'],
            'seq' => $data['seq'],
            'creator' => (integer)$data['creator'],
            'room_id' => $data['roomID'],
            'pay_type'=> $pay_type,
            'paizu_time' => (integer)$timestamp
        ];

        $tableName = 'log_paiju_ext_'.date('Ym',$timestamp);
        $ret = $this->mysql('logs')->insert($tableName, $payData);
        if (!$ret) {
            $this->e('牌局类型日志保存失败', $payData);
        }

        return $juData;
    }

    /**
     * 保存牌组
     * @param $data
     * @param $juData
     * @return bool
     */
    public function savePaizuInfo($data, $juData)
    {
        $where = array(
            'paiZuID' => $data['paiZuID']
        );

        /**
         * 保存数据
         */
        $exists = false;
        if ($exists) {
            /**
             * 已存在则更新记录
             */
            unset($data['paiZuID'], $data['seq']);
            /**
             * 统计牌局
             */
            $fields = 'SUM(score1) AS totalScore1,
            SUM(score2) AS totalScore2,
            SUM(score3) AS totalScore3,
            SUM(score4) AS totalScore4';
            $result = $this->mysql('logs')->findRow($this->juTable, $where, $fields);
            if ($result) {
                $zuData['score1'] = $result['totalScore1'];
                $zuData['score2'] = $result['totalScore2'];
                $zuData['score3'] = $result['totalScore3'];
                $zuData['score4'] = $result['totalScore4'];
            }
            if ($data['seq'] == 1) {
                $zuData['startTime'] = $data['time'];
            }
            $result = $this->mysql('logs')->update($this->zuTable, $zuData, $where);
        } else {
            /**
             * 不存在则插入记录
             */
            for($i=0; $i < count($data['uids']); $i++) {
                if($data['uids'][$i] == 0) continue;
                $zuData = array();
                $zuData['uid'] = $data['uids'][$i];
                $zuData['paiju_score'] = isset($data['detail']['score'][$i][0])? $data['detail']['score'][$i][0]:NULL;
                $zuData['paizu_score'] = isset($data['detail']['score'][$i][1])? $data['detail']['score'][$i][1]:NULL;
                $zuData['time'] = date("Y-m-d H:i:s", $data['time']);
                $zuData['paizu_id'] = $data['paiZuID'];
                $zuData['seq'] = $data['seq'];
                $zuData['room_id'] = $data['roomID'];
                $zuData['server_id'] = $data['serverID'];
                $zuData['creator'] = (integer)$data['creator']; //这个字段才加，测试环境旧数据没有，所以加上integer转换
                
                // add by lyon 增加局数加入牌局日志 17/04/28
                if (isset($data['juShu'])) {
                    $zuData['jushu'] = $data['juShu'];
                }
                
                // xiaocui 增加俱乐部id  2018-07-26
                if(isset($data['clubID'])){
                    $zuData['club_id'] = intval($data['clubID']);
                }

                $result = $this->mysql('logs')->insert($this->zuTable, $zuData);
                if (!$result) {
                    $this->e('save_error', $this->mysql('logs')->error());
                    $this->e('用户牌局日志保存失败', $zuData);
                    return [];
                }
            }
        }
        return $zuData;
    }

    /**
     * 获取房间最新牌组
     * @param $roomID
     */
    public function getLatestByRoom($roomID)
    {
        if ($roomID) {
            $where = ['roomID' => $roomID];
            $option = [
                'fields' => '',
                'order' => 'startTime DESC',
                'limit' => '1'
            ];
            $result = $this->mysql('logs')->findRow($this->zuTable, $where, $option);
            return $result;
        }

        return [];
    }


    public function backup2db($obj, $visitNum)
    {
        $len = strpos($obj['paiZuID'], '_');
        $len = $len > 10 ? 0 : $len;
        $timestamp = $len > 0 ? substr($obj['paiZuID'], 0, $len) : 0;
        $data = [
            'paizu_id' => $obj['paiZuID'],
            'seq' => $obj['seq'],
            'creator' => empty($obj['creator']) ? 0 : $obj['creator'] ,
            'room_id' => $obj['roomID'],
            'server_id' => $obj['serverID'],
            'uids' => $obj['uids'],
            'detail' => base64_encode( $obj['detail'] ),
            'paizu_time' => $timestamp,
            'juShu' => empty($obj['juShu']) ? 0 : $obj['juShu'],
            'v_time' => empty($obj['createTime']) ? time() : $obj['createTime'],
            'v_uid' =>  empty($obj['creator']) ? 0 : $obj['creator'] ,
            'v_num' => $visitNum,

        ];
        $result = $this->mysql('logs')->insert('log_paiju_visit', $data);
        if (!$result) {
            $this->e('save_error', $this->mysql('logs')->error());
            $this->e('***222******', $data);
            return [];
        }
    }

    public function savePaijuLogExt() {
        $result = $this->mysql('logs')->findRow('log_paiju',['room_id'=>'181823']);
        // 保存支付类型日志
        $payData = [
            'paizu_id' => $result['paizu_id'],
            'seq' => $result['seq'],
            'creator' => (integer)$result['creator'],
            'room_id' => $result['room_id'],
            'pay_type'=> 1,
            'paizu_time' => $result['paizu_time'],
        ];

        $tableName = 'log_paiju_ext_'.date('Ym',$result['paizu_time']);
        $result = $this->mysql('logs')->insert($tableName, $payData);
        if (!$result) {
            echo 11;
            $this->e('牌局类型日志保存失败', $payData);
        }
    }
}